<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Lines 3D 1</title>
    <link rel="stylesheet" href="../include/style.css">
  </head>
  <body>
    <header>
      Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
    </header>
    <canvas id="canvas" width="400" height="400"></canvas>
    <aside>Move mouse on canvas element.</aside>

    <script src="../include/utils.js"></script>
    <script src="./classes/ball3d.js"></script>
    <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d'),
          mouse = utils.captureMouse(canvas),
          balls = [],
          numBalls = 15,
          fl = 250,
          vpX = canvas.width / 2,
          vpY = canvas.height / 2,
          angleX, angleY;

      for (var ball, i = 0; i < numBalls; i++) {
        ball = new Ball3d(5, "#000000");
        ball.xpos = Math.random() * 200 - 100;
        ball.ypos = Math.random() * 200 - 100;
        ball.zpos = Math.random() * 200 - 100;
        balls.push(ball);
      }

      function rotateX (ball, angle) {                      
        var cos = Math.cos(angle),
            sin = Math.sin(angle),
            y1 = ball.ypos * cos - ball.zpos * sin,
            z1 = ball.zpos * cos + ball.ypos * sin;
        ball.ypos = y1;
        ball.zpos = z1;
      }
      
      function rotateY (ball, angle) {
        var cos = Math.cos(angle),
            sin = Math.sin(angle),
            x1 = ball.xpos * cos - ball.zpos * sin,
            z1 = ball.zpos * cos + ball.xpos * sin;
        ball.xpos = x1;
        ball.zpos = z1;
      }

      function setPerspective (ball) {
        if (ball.zpos > -fl) {
          var scale = fl / (fl + ball.zpos);
          ball.scaleX = ball.scaleY = scale;
          ball.x = vpX + ball.xpos * scale;
          ball.y = vpY + ball.ypos * scale;
          ball.visible = true;
        } else {
          ball.visible = false;
        }
      }

      function move (ball, i) {
        rotateX(ball, angleX);
        rotateY(ball, angleY);
        setPerspective(ball);
        //don't draw line to first ball
        if (i !== 0) {
          context.lineTo(balls[i].x, balls[i].y);
        }
      }

      function draw (ball) {
        if (ball.visible) {
          ball.draw(context);
        }
      }

      (function drawFrame () {
        window.requestAnimationFrame(drawFrame, canvas);
        context.clearRect(0, 0, canvas.width, canvas.height);

        angleX = (mouse.y - vpY) * 0.001;
        angleY = (mouse.x - vpX) * 0.001;
        context.beginPath();
        //line starts at first ball
        context.moveTo(balls[0].x, balls[0].y);
        balls.forEach(move);
        context.stroke();
        balls.forEach(draw);
      }());
    };
    </script>
  </body>
</html>
